package com.mgq.netty.chat.client;

import com.mgq.netty.chat.message.*;
import com.mgq.netty.chat.protocol.MessageCodecShare;
import com.mgq.netty.chat.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author MaGuangQi
 * @description
 * @date 2021-12-07 17:19
 **/
@Slf4j
public class ChatClient {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOG_HANDLER = new LoggingHandler();
        MessageCodecShare MES_CODEC = new MessageCodecShare();


        //使用CountDownLatch2个线程进行通信
        CountDownLatch WAIT_FOR_LOGIN = new CountDownLatch(1);
        AtomicBoolean LOGIN = new AtomicBoolean(false);
        ChannelFuture future = new Bootstrap()
                .group(group)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProtocolFrameDecoder());
                        ch.pipeline().addLast(LOG_HANDLER);
                        ch.pipeline().addLast(MES_CODEC);
                        //3 秒没有写,产生写事件
                        ch.pipeline().addLast(new IdleStateHandler(0, 3, 0));
                        ch.pipeline().addLast(new ChannelDuplexHandler() {
                            @Override
                            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                ctx.writeAndFlush(new PingMessage());
                            }
                        });
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {

                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                new Thread(() -> {
                                    //建立连接后
                                    Scanner scanner = new Scanner(System.in);
                                    System.out.println("请输入用户名");
                                    String username = scanner.nextLine();
                                    System.out.println("请输入密码");
                                    String password = scanner.nextLine();
                                    LoginRequestMessage requestMessage = new LoginRequestMessage(username, password);
                                    ctx.writeAndFlush(requestMessage);
                                    try {
                                        //等待
                                        WAIT_FOR_LOGIN.await();
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                    //登录失败
                                    if (!LOGIN.get()) {
                                        ctx.channel().close();
                                        return;
                                    }
                                    // 打印菜单
                                    while (true) {
                                        System.out.println("============ 功能菜单 ============");
                                        System.out.println("send [username] [content]");
                                        System.out.println("gsend [group name] [content]");
                                        System.out.println("gcreate [group name] [m1,m2,m3...]");
                                        System.out.println("gmembers [group name]");
                                        System.out.println("gjoin [group name]");
                                        System.out.println("gquit [group name]");
                                        System.out.println("quit");
                                        System.out.println("==================================");
                                        String[] command = scanner.nextLine().split(" ");
                                        String name = command[0];
                                        switch (name) {
                                            case "send":
                                                ChatRequestMessage send = new ChatRequestMessage(username, command[1], command[2]);
                                                ctx.writeAndFlush(send);
                                                break;
                                            case "gsend":
                                                GroupChatRequestMessage groupChatRequestMessage = new GroupChatRequestMessage(username, command[1], command[2]);
                                                ctx.writeAndFlush(groupChatRequestMessage);
                                                break;
                                            case "gcreate":
                                                HashSet<String> receivers = new HashSet<>(Arrays.asList(command[2].split(",")));
                                                //把自己加入
                                                receivers.add(username);
                                                GroupCreateRequestMessage groupCreateRequestMessage = new GroupCreateRequestMessage(command[1], receivers);
                                                ctx.writeAndFlush(groupCreateRequestMessage);
                                                break;
                                            case "gmembers":
                                                GroupMembersRequestMessage groupMembersRequestMessage = new GroupMembersRequestMessage(command[1]);
                                                ctx.writeAndFlush(groupMembersRequestMessage);
                                                break;
                                            case "gjoin":
                                                GroupJoinRequestMessage groupJoinRequestMessage = new GroupJoinRequestMessage(username, command[1]);
                                                ctx.writeAndFlush(groupJoinRequestMessage);
                                                break;
                                            case "gquit":
                                                GroupQuitRequestMessage groupQuitRequestMessage = new GroupQuitRequestMessage(username, command[1]);
                                                ctx.writeAndFlush(groupQuitRequestMessage);
                                                break;
                                            case "quit":
                                                ctx.channel().close();
                                                return;
                                            default:
                                                System.out.println("指令错误,请重新输入");
                                        }
                                    }

                                }, "system in").start();
                            }

                            @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                log.debug("连接被断开...按任意键退出");
                                new Scanner(System.in);
                                ctx.channel().close();

                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                log.debug("连接被异常断开...按任意键退出");
                                new Scanner(System.in);
                                ctx.channel().close();
                                log.debug("异常信息{}", cause.getMessage());
                            }

                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                if (msg instanceof LoginResponseMessage) {
                                    LoginResponseMessage message = (LoginResponseMessage) msg;
                                    if (message.isSuccess()) {
                                        LOGIN.set(true);
                                    }
                                    WAIT_FOR_LOGIN.countDown();
                                }
                                log.debug("msg:{}", msg);
                            }
                        });
                    }
                }).connect(new InetSocketAddress("localhost", 8080));

        future.sync();
        //这个位置连接已经建立
        future.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //关闭group,退出客户端
                group.shutdownGracefully();
            }
        });
    }
}
